<?php

namespace plugin\muadmin\app\common\model;

use plugin\muadmin\app\common\core\AdminAuth;
use think\Model;

class Admin extends Model
{
    protected $name = 'admin';
    protected $autoWriteTimestamp = 'datetime';
    protected $pk = 'id';
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    public function authgroup()
    {
        $group_ids = AuthGroupAccess::where('uid', $this->id)
            ->column('group_id');
        $names = AuthGroup::where('id', 'in', $group_ids)
            ->column('name');
        return !empty($names)?$names:[];
    }

    /**
     * 记录日志
     * @param $request
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function record($request)
    {
        $log = [
            'url'=>$request->path(),
            'content'=>json_encode($request->all(),JSON_PARTIAL_OUTPUT_ON_ERROR|JSON_UNESCAPED_SLASHES),
            'ip'=>$request->getRealIp(true),
            'useragent'=>$request->protocolVersion()
        ];
        $auth = AdminAuth::getInstance();
        if(!empty($auth)){
            if($auth->isLogin()){
            $log['admin_id'] = $auth->id;
            $log['username'] = $auth->userName;
            }
        }
        $rule = AuthRule::where([
            ['route','=',$request->baseController.'/'.$request->action],
            ['plugin','=',$request->plugin],
            ['module','=',$request->app],
        ])->find();
        if(!empty($rule)){
            $log['title'] = __($rule->title);
        }
        AdminLog::create($log);
    }
}